package com.zja.service.Impl;

import com.zja.dao.Impl.KnowledgeBaseAdminDaoImpl;
import com.zja.dao.Impl.KnowledgeBaseDaoImpl;
import com.zja.dao.KnowledgeBaseAdminDao;
import com.zja.dao.KnowledgeBaseDao;
import com.zja.model.KnowledgeBase;
import com.zja.service.KnowledgeBaseService;

import java.util.ArrayList;
import java.util.List;


/**
 * @author JA
 * @date: 2025/5/3
 * description:
 */
public class KnowledgeBaseServiceImpl implements KnowledgeBaseService {
    private final KnowledgeBaseDao knowledgeBaseDao = new KnowledgeBaseDaoImpl();
    private final KnowledgeBaseAdminDao knowledgeBaseAdminDao = new KnowledgeBaseAdminDaoImpl();

    @Override
    public List<KnowledgeBase> getAll() {
        return knowledgeBaseDao.selectAll();
    }

    @Override
    public KnowledgeBase getById(Long id) {
        return knowledgeBaseDao.selectById(id);
    }

    @Override
    public boolean create(KnowledgeBase kb) {
        return knowledgeBaseDao.insert(kb);
    }

    @Override
    public boolean update(KnowledgeBase kb) {
        return knowledgeBaseDao.update(kb);
    }

    @Override
    public boolean delete(Long id) {
        return knowledgeBaseDao.deleteById(id);
    }

    @Override
    public List<KnowledgeBase> getByCreatorId(Long creatorId) {
        List<KnowledgeBase> all = knowledgeBaseDao.selectAll();
        List<KnowledgeBase> result = new ArrayList<>();
        for (int i = 0; i < all.size(); i++) {
            KnowledgeBase kb = all.get(i);
            if (kb.getCreatorId() != null && kb.getCreatorId().equals(creatorId)) {
                result.add(kb);
            }
        }
        return result;
    }

    @Override
    public boolean isAlreadyAdmin(Long kbId, Long userId) {
        return knowledgeBaseAdminDao.isUserAdmin(kbId, userId);
    }

    @Override
    public boolean addKnowledgeBaseAdmin(Long kbId, Long userId) {
        return knowledgeBaseAdminDao.addAdmin(kbId, userId);
    }

    @Override
    public boolean userHasManagePermission(Long userId, Long kbId) {
        try {
            // 查询 knowledge_base 表
            KnowledgeBase kb = knowledgeBaseDao.selectById(kbId);
            if (kb == null) {
                return false;
            }
            if (kb.getCreatorId().equals(userId)) {
                return true;
            }

            // 查询 knowledgebase_admins
            List<Long> adminIds = knowledgeBaseDao.selectAdminIdsByKbId(kbId);
            return adminIds.contains(userId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<KnowledgeBase> getAllManagedKnowledgeBases(Long userId) {
        return knowledgeBaseDao.selectAllByAdminUserId(userId);
    }
}


